2017-07-31 76 views
0

我想通过微软的Graph API从Azure Active Directory中读取用户的数据。使用图形浏览器,我可以获得所有用户,但使用独立应用程序后,我收到令牌后最终会收到“未经授权”的响应。我显然错过了一些步骤,但对我而言,这不是很明显。任何有识之士将不胜感激Microsoft Graph Api令牌无效或未经授权?

下面的代码是基于断MSFT样本:

// config values 
// authority = "https://login.microsoftonline.com/{ TENANT ID }/oauth2/" 
// resource uri = "https:// APP NAME .azurewebsites.net"; 
// graph uri = https://graph.windows.net/TENANT ID/ also tried https://graph.windows.net/v1.0/ 


// short form 
public async void GetUsers(ADConfiguration config) 
{ 
    _authContext = new AuthenticationContext(config.GetAuthority()); 
    _clientCredential = new ClientCredential(config.ClientId, config.ClientSecret); 

    AuthenticationResult result = null; 

    // obtain the token, this part is still successful 
    result = await _authContext.AcquireTokenAsync(config.ResourceUri, _clientCredential); 

    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); 


    string address = config.GetGraphiUri() + "users?api-version=1.6"; 

    // this response is always unauthorized 
    HttpResponseMessage response = await _httpClient.GetAsync(address); 

} 

回答

0

你的配置值似乎关:

管理局应该是:https://login.microsoftonline.com/{TENANT ID}

在我看来,您正在尝试使用Azure AD Graph API,而不是Microsoft Graph API。

在这种情况下:

资源URI应该是:https://graph.windows.net/。 (MS Graph API是https://graph.microsoft.com/

+0

感谢您的回答。建议将错误消息从“未授权”更改为“禁止”。一个横向移动我猜... 我相信资源uri是指Azure上的AD服务器。无论哪种方式,我尝试过任何变化没有太多的成功。 – Mark

+0

禁止表示您的应用程序没有必要的权限。检查是否已将它们添加到Azure AD Graph。 – juunas

+0

我们有两个可以访问的API:'Windows Azure Active Directory'和'Microsoft Graph',它们都有权限执行所有操作。我已经在寻找'Azure AD Graph'来添加API访问权限,但是这不会作为选项提供。 – Mark

1

除了回答你的新问题。从您的代码中,您使用client credential flow获取令牌。在客户端凭证流程中,权限直接授予应用程序本身。

由于您使用Azure的AD图形API,你需要添加application permission

  1. 在Azure的门户网站,选择您的应用程序,点击Settings
  2. 在设置菜单中,选择Required permissions部分,选择Windows Azure Active Directory(Azure广告图api),添加您的应用所需的相关应用程序权限。
  3. 在您的应用程序的刀片中,点击Grant Permissions以执行管理员对您的管理员凭据的同意。
+0

谢谢,就像我告诉Juunas,我们有两个可以访问的API:'Windows Azure Active Directory'和'Microsoft Graph',它们都有权限执行所有操作。 我怀疑我在这里忽略了一些基本的东西...... – Mark

+0

请使用[此工具](http://jwt.calebb.net/)解码您的访问令牌,并检查是否包含在角色中的任何应用程序权限 –

+0

Nan指出你的令牌解码器网站未来可能会消失。请使用此代替(功能相同):https://jwtinspect.azurewebsites.net/。 @Mark是您使用AAD还是Microsoft Graph的API?无论哪种情况,如果您使用的是client_credentials流程,则管理员需要授予您的API调用的许可/权限才能发挥作用。 –

相关问题