OAuth2身份验证和Unity中的操作 [英] OAuth2 Authentication and Operations in Unity

查看:101
本文介绍了OAuth2身份验证和Unity中的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为Unity中的Windows Mobile应用程序实现OAuth2身份验证和一些操作.我设法使它作为控制台应用程序运行(使用.NET 4.0及更高版本),但是Unity最多支持.NET 3.5,因此仅复制代码是行不通的.有什么方法可以使其在Unity中工作? 这是我的验证码:

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();
        }
    }

这是我的OAuth2函数之一:

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!

推荐答案

将其转换成旧的.NET版本并不难.您可以使用Unity的 WWW

It's not really that hard to translate to old .NET version. You can use Unity's WWW or UnityWebRequest API. Any of them should do it.

1 .将HttpClient替换为 UnityWebRequest .

1.Replace HttpClient with UnityWebRequest.

2 .用Dictionary替换KeyValuePair.

3 .将DefaultRequestHeaders替换为 .

4 .将client.PostAsync替换为

5 .对于Json,请使用unity的 JsonUtility

5.For Json, use unity's JsonUtility

6 .对于GetMeasurements函数中的Json数组,请使用 JsonHelper 这篇文章中的课程.

6.For Json array in your GetMeasurements function, use the JsonHelper class from this post.

就是这样.我能够进行快速移植.没有测试它,但是它能够编译,应该让您入门.

That's it. I was able to do a quick porting. Didn't test it but it was able to compile and should get you started.

GetAccessToken函数:

[Serializable]
public class TokenClassName
{
    public string access_token;
}

private static IEnumerator GetAccessToken(Action<string> result)
{
    Dictionary<string, string> content = new Dictionary<string, string>();
    //Fill key and value
    content.Add("grant_type", "client_credentials");
    content.Add("client_id", "login-secret");
    content.Add("client_secret", "secretpassword");

    UnityWebRequest www = UnityWebRequest.Post("https://someurl.com//oauth/token", content);
    //Send request
    yield return www.Send();

    if (!www.isError)
    {
        string resultContent = www.downloadHandler.text;
        TokenClassName json = JsonUtility.FromJson<TokenClassName>(resultContent);

        //Return result
        result(json.access_token);
    }
    else
    {
        //Return null
        result("");
    }
}

GetMeasurements函数:

[Serializable]
public class MeasurementClassName
{
    public string Measurements;
}

private static IEnumerator GetMeasurements(string id, DateTime from, DateTime to, Action<string> result)
{
    Dictionary<string, string> content = new Dictionary<string, string>();
    //Fill key and value
    content.Add("MeasurePoints", id);
    content.Add("Sampling", "Auto");
    content.Add("From", from.ToString("yyyy-MM-ddTHH:mm:ssZ"));
    content.Add("To", to.ToString("yyyy-MM-ddTHH:mm:ssZ"));
    content.Add("client_secret", "secretpassword");

    UnityWebRequest www = UnityWebRequest.Post("https://someurl.com/api/v2/Measurements", content);

    string token = null;

    yield return GetAccessToken((tokenResult) => { token = tokenResult; });

    www.SetRequestHeader("Authorization", "Bearer " + token);
    www.Send();

    if (!www.isError)
    {
        string resultContent = www.downloadHandler.text;
        MeasurementClassName[] rootArray = JsonHelper.FromJson<MeasurementClassName>(resultContent);

        string measurements = "";
        foreach (MeasurementClassName item in rootArray)
        {
            measurements = item.Measurements;
        }

        //Return result
        result(measurements);
    }
    else
    {
        //Return null
        result("");
    }
}

用法:

string id = "";
DateTime from = new DateTime();
DateTime to = new DateTime();

StartCoroutine(GetMeasurements(id, from, to, (measurementResult) =>
{
    string measurement = measurementResult;

    //Do something with measurement
    UnityEngine.Debug.Log(measurement);

}));

这篇关于OAuth2身份验证和Unity中的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆