I need to implement OAuth2 authentication and some operations for a Windows Mobile application in Unity. I have managed to make it work as a console application (using .NET 4.0 and above), however, Unity only supports up until .NET 3.5, so simply copying the code didn't work. Is there any way to make it work in Unity? Here is my authentication code:
private static async Task<string> GetAccessToken()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://someurl.com");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", "login-secret"),
new KeyValuePair<string, string>("client_secret", "secretpassword")
});
var result = await client.PostAsync("/oauth/token", content);
string resultContent = await result.Content.ReadAsStringAsync();
var json = JObject.Parse(resultContent);
return json["access_token"].ToString();
}
}
And this is one of my OAuth2 functions:
private static async Task<string> GetMeasurements(string id, DateTime from, DateTime to)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://someurl.com");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("MeasurePoints", id),
new KeyValuePair<string, string>("Sampling", "Auto"),
new KeyValuePair<string, string>("From", from.ToString("yyyy-MM-ddTHH:mm:ssZ")),
new KeyValuePair<string, string>("To", to.ToString("yyyy-MM-ddTHH:mm:ssZ"))
});
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken().Result);
var result = await client.PostAsync("/api/v2/Measurements", content);
string resultContent = await result.Content.ReadAsStringAsync();
var rootArray = JArray.Parse(resultContent);
string measurements = "";
foreach (JObject item in rootArray)
{
measurements = item.GetValue("Measurements").ToString();
}
return measurements;
}
}
If you have any suggestions, I will be grateful for eternity. Thanks!