MSGraph使用正确的令牌对动态进行身份验证可获得401

时间:2017-05-11 15:38:20

标签: authentication microsoft-dynamics microsoft-graph

使用以下代码我可以连接到MSGraph(不同的资源URL)并获取我需要的数据,但我很难意识到如何为Microsoft Dynamics(CRM)做同样的事情

public static async Task<string> GetTokenForApplication(string resourceUrl)
{
    AuthenticationContext authenticationContext = 
         new AuthenticationContext(AppModeConstants.AuthString, false);

    ClientCredential clientCred = new ClientCredential(AppModeConstants.ClientId, AppModeConstants.ClientSecret);
    AuthenticationResult authenticationResult = await authenticationContext
           AcquireTokenAsync("resourceUrl", clientCred);

    TokenForApplication = authenticationResult.AccessToken;
}

public static async Task CrmTest()
{
        var token = await AuthenticationHelper.GetTokenForApplication(@"https://myapp.crm4.dynamics.com/");

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await client.GetAsync(@"https://myapp.crm4.dynamics.com/api/data/v8.2/accounts");
}

虽然我拿到了正确的令牌,但我仍然会得到401:未经授权:

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  REQ_ID: 790b38b0-c8c0-4878-a318-e490ee7db57a
  Strict-Transport-Security: max-age=31536000; includeSubDomains
  Date: Thu, 11 May 2017 15:33:41 GMT
  Set-Cookie: crmf5cookie=!UXdAbawdawdal8sNiJ9xy74dAiawdawdDnDsomethingAolDYjkR7innjWIYQ1pV+DcZ9A=;secure; path=/
  Server: Microsoft-IIS/8.5
  WWW-Authenticate: Bearer authorization_uri=https://login.windows.net/b8faag21-awda-awda-90s4-f8652ss86ddb/oauth2/authorize, resource_id=https://myapp.crm4.dynamics.com/
  X-Powered-By: ASP.NET
  Content-Length: 49
  Content-Type: text/html
}}

我理解的是403,但401意味着我只是使用了错误的身份验证。对此的任何意见都将不胜感激。

编辑:甚至可以将CRM数据作为应用程序访问吗? azure门户中只有委派的权限,没有应用程序权限。

1 个答案:

答案 0 :(得分:0)

虽然Dynamics CRM和Graph都利用Azure AD帐户,但它们具有不同的权限范围和先决条件。

要开始使用,您需要关注此Walkthrough: Register a Dynamics 365 app with Azure Active Directory