Unity 中的 OAuth2 身份验证和操作 [英] OAuth2 Authentication and Operations in 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
或 UnityWebRequest
API.他们中的任何一个都应该这样做.
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
替换为 SetRequestHeader
.
3.Replace DefaultRequestHeaders
with SetRequestHeader
.
4.用 client.PostAsync="noreferrer">UnityWebRequest.Send
4.Replace client.PostAsync
with UnityWebRequest.Send
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);
}));
这篇关于Unity 中的 OAuth2 身份验证和操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!