我正在使用需要连接到使用OAuth2.0的Microsoft Dynamics 365的Unity应用程序。我正在尝试使用UnityWebRequest通过调用来检索访问令牌:
https://login.microsoftonline.com/[TENANT_ID]/oauth2/v2.0/token
使用类似于这个线程的东西:
OAuth2 Authentication and Operations in Unity
并且它有效,我能够获得和access_token,但是,当我尝试使用Bearer令牌消费服务时,我总是得到“401未授权”。
然后我试着打电话:
https://login.microsoftonline.com/[TENANT_ID]/oauth2/v2.0/authorize
但是,当我这样做时,响应是Microsoft登录屏幕的实际HTML代码。据我所知,获取身份验证代码需要用户交互吗?但是我已经能够通过在没有用户交互的控制台C#app中使用NuGet的Microsoft.IdentityModel.Clients.ActiveDirectory包来完成这项工作,所以一定有办法吗?
我真的很感谢你的帮助!谢谢!
更新1 - 我的代码
获取访问令牌
private IEnumerator GetAccessToken(Action<string> result)
{
Dictionary<string, string> content = new Dictionary<string, string>();
//Fill key and value
content.Add("scope", "https://graph.microsoft.com/.default");
content.Add("grant_type", "client_credentials");
content.Add("client_id", "xxxxx");
content.Add("client_secret", "xxxx");
UnityWebRequest www = UnityWebRequest.Post("https://login.microsoftonline.com/[TENANTID]/oauth2/v2.0/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("");
}
}
调用API
private IEnumerator GetData(Action<string> result)
{
Dictionary<string, string> content = new Dictionary<string, string>();
//Fill key and value
content.Add("CustomerGroupId", "10");
UnityWebRequest www = UnityWebRequest.Post("https://[ENVIRONMENT].cloudax.dynamics.com/data/TestEntity", content);
string token = null;
yield return GetAccessToken((tokenResult) => { token = tokenResult; });
result(token);
www.SetRequestHeader("Authorization", "Bearer " + token);
www.Send();
if (!www.isError)
{
string resultContent = www.downloadHandler.text;
// Perform additional operations...
}
}
令牌和API调用的资源不同。在令牌请求中,资源是https://graph.microsoft.com
,它不是您的目标API。您应该为目标API请求令牌。