簡體   English   中英

REST服務的身份驗證問題使用來自WP8應用程序的HttpClient

[英]Problems with the authentication to a REST service use `HttpClient` from an `WP8` App

我試圖用一些需要身份驗證的Rest服務來連接我的應用程序,但出現了一些問題。 我使用HttpClient類,它與不需要這種身份驗證的服務(如登錄名或注冊名)一起正常工作。 我認為問題在於我需要在AuthenticationHeaderValue對象中指定一個架構,並且該架構會進入標頭。 標頭的結果如下所示:“授權:授權a81b4974-f328-44e0-901a-95e29fb672aa:sKJQgOqJswCLHlibsMGRYZb / dlkyPzVnvs9uqqx5ToM =“,服務器正在尋找的內容類似於“授權:a81b294-f901-672 sKJQgOqJswCLHlibsMGRYZb / dlkyPzVnvs9uqqx5ToM =“這是我正在使用的代碼:

public async void addProject(string name) 
{
    string service = "/service/project/add";
    string serviceURL = "/pwpcloud"+service;
    StringBuilder parametersBuilder = new StringBuilder();

    parametersBuilder.Append("{\"name\":\"" + name + "\",");
    parametersBuilder.Append("\"description\":\"" + "projectDescription" + "\",");
    parametersBuilder.Append("\"sparsePath\":\"" + "fasdd" + "\",");
    parametersBuilder.Append("\"densePath\":\"" + "asdf" + "\",");
    parametersBuilder.Append("\"matchFormat\":\"" + "asdf" + "\",");
    parametersBuilder.Append("\"metadata\":\"" + "aaaaa" + "\",");
    parametersBuilder.Append("\"user\":\"" + mLoginData.getUserID() + "\"}");

    string parameters = parametersBuilder.ToString();

    HttpClient restClient = new HttpClient();
    restClient.BaseAddress = new Uri(mBaseURL);
    restClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    //falta la autenticacion
    setAuthorization(restClient, service, WEBSERVICE_REQUEST_TYPE_POST);
    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, serviceURL);
    req.Content = new StringContent(parameters, Encoding.UTF8, "application/json");
    HttpResponseMessage response = null;
    string responseBodyAsText = "";
    try
    {
        response = await restClient.SendAsync(req);
        response.EnsureSuccessStatusCode();
        responseBodyAsText = await response.Content.ReadAsStringAsync();
    }
    catch (HttpRequestException e)
    {
        string ex = e.Message;
    }
}

public void setAuthorization(HttpClient request, string service, int reqType, string token, string userID)
{
    //Date OK
    string date = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");

    //nonce OK
    Random random = new Random();
    String nonce = "";
    for (int i = 0; i < 5; i++)
    {
        string randomValue = (1111 + random.Next() % (9999 - 1111)).ToString();
        nonce = nonce + randomValue;
    }
    //type OK
    string type = "";
    if (reqType == WEBSERVICE_REQUEST_TYPE_GET)
    {
        type = "GET";
    }
    else
    {
        type = "POST";
    }

    //Authorization:
    string stringToHash = token + ":" + service + "," + type + "," + date + "," + nonce;
    string authorizationCrypted = encryptStringSHA256(stringToHash);
    //string authorization = userID + ":" + authorizationCrypted;
    request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", string.Format("{0}:{1}", userID, authorizationCrypted));

    request.DefaultRequestHeaders.Add("x-rest-date", date);
    request.DefaultRequestHeaders.Add("nonce", nonce);
}
public static string encryptStringSHA256(string stringToEncrypt)
{
    var hash = new SHA256Managed();

    byte[] stringHash = StringToAscii(stringToEncrypt);
    byte[] encryptedString = hash.ComputeHash(stringHash);
    return Convert.ToBase64String(encryptedString);
}

//Metodo para convertir string a bytes ascii NO IMPLEMENTADO POR DEFECTO EN EL API DE WINDOWS PHONE
public static byte[] StringToAscii(string s)
{
    byte[] retval = new byte[s.Length];
    for (int ix = 0; ix < s.Length; ++ix)
    {
        char ch = s[ix];
        if (ch <= 0x7f) retval[ix] = (byte)ch;
        else retval[ix] = (byte)'?';
    }

    return retval;
}

謝謝您的幫助。

我使用HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Key",value)方法解決了此問題。 這是代碼:

public void setAuthorization(HttpClient request, string service, int reqType, string token, string userID)
{
    //Date OK
    string date = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");

    //nonce OK
    Random random = new Random();
    String nonce = "";
    for (int i = 0; i < 5; i++)
    {
        string randomValue = (1111 + random.Next() % (9999 - 1111)).ToString();
        nonce = nonce + randomValue;
    }
    //type OK
    string type = "";
    if (reqType == WEBSERVICE_REQUEST_TYPE_GET)
    {
        type = "GET";
    }
    else
    {
        type = "POST";
    }

    //Authorization:
    string stringToHash = token + ":" + service + "," + type + "," + date + "," + nonce;
    string authorizationCrypted = encryptStringSHA256(stringToHash);
    string authorization = userID + ":" + authorizationCrypted;
    request.DefaultRequestHeaders.TryAddWithoutValidation("x-rest-date", date);
    request.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authorization);
    request.DefaultRequestHeaders.TryAddWithoutValidation("nonce", nonce);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM