Azure Active Directory图谱API授权无法为用户获取组

时间:2015-08-09 12:54:42

标签: c# asp.net-mvc azure authorization azure-active-directory

首先,我使用以下内容实现基于角色的访问:

http://www.codeproject.com/Articles/749588/Role-Based-Access-Control-with-Azure-Active-Direct

部署后,我正在使用 localhost url 运行FINE我遇到以下错误:

远程服务器返回错误:(401)未经授权。 [ActiveDirectoryAuthenticationException:AADSTS70002:验证凭据时出错。 AADSTS50012:提供了无效的客户端密钥。 跟踪ID:b672d4b0-eccc-45b2-97e8-0f9c8c916aea 相关ID:dcb4bad8-e449-4919-832d-0791eef24570

为了解决这个问题,我在Azure目录中创建了一个新应用程序,并使用应用程序的客户端ID和密码授予所有权限并更新了web.config。

但仍然得到同样的错误。因此决定手动完成:

使用以下代码

  string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;

        // Get a token for calling the Windows Azure Active Directory Graph
        AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, LoginUrl, tenantId));
        ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey);
        AuthenticationResult assertionCredential = authContext.AcquireToken(GraphUrl, credential);
        string authHeader = assertionCredential.CreateAuthorizationHeader();

获取所有用户

    private static readonly string GraphAllUsersUrl = "https://graph.windows.net/{0}/users?api-version=2013-04-05";
 string requestUrl = String.Format(
                CultureInfo.InvariantCulture,
                GraphAllUsersUrl,
                HttpUtility.UrlEncode(tenantId));

            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            request.Headers.TryAddWithoutValidation("Authorization", authHeader);
            HttpResponseMessage response = await client.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();

工作正常。

现在获取用户的所有组:

       private static readonly string UserGroupsUrl = "https://graph.windows.net/{0}/users/{1}/memberOf?api-version=2013-04-05";
 string requestUrl2 = String.Format(
               CultureInfo.InvariantCulture,
               UserGroupsUrl,
               HttpUtility.UrlEncode(tenantId),
               HttpUtility.UrlEncode(ClaimsPrincipal.Current.Identity.Name)
               );
      HttpRequestMessage request2 = new HttpRequestMessage(HttpMethod.Get, requestUrl2);
                request.Headers.TryAddWithoutValidation("Authorization", authHeader);
                HttpResponseMessage response2 = await client.SendAsync(request2);
                string responseString2 = await response2.Content.ReadAsStringAsync();

它会抛出相同的授权错误。

在搜索时,我发现在清单文件中设置了一些内容,我确实没有运气。

0 个答案:

没有答案