尽管授予了所有必要的权限,但“权限不足,无法完成操作”

时间:2020-02-15 07:07:27

标签: c# api azure-active-directory microsoft-graph-api

swiper

我能够从服务器检索身份验证令牌,并已通过AAD授予了所有权限,但是我仍然面临着同样的问题。 如果有人可以帮助我,那将很棒。 我正在使用Microsoft Graph API。

下面是我正在使用的代码

{"odata.error":{"code":"Authorization_RequestDenied",
"message":
{"lang":"en","value":"Insufficient privileges to complete the operation."},
"requestId":"b205e5d0-f929-418e-9153-f1994e2c0893",
"date":"2020-02-15T06:53:57"}
}

1 个答案:

答案 0 :(得分:0)

我尝试了以下方法,并为我完美地工作了。

       //Token Request End Point
        string tokenUrl = $"https://login.microsoftonline.com/yourTenant.onmicrosoft.com/oauth2/token";
        var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

        //I am Using client_credentials as It is mostly recommended
        tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = "b603c7be-a956_Your_Client_Id_a45996-e6921e61f36955",
            ["client_secret"] = "Vxf1SluKbgu4PF0loj_Your_Client_Secret_okjh8wL/yujh45lojhgg=",
            ["resource"] = "https://graph.windows.net" 
        });

        dynamic json;
        AccessTokenClass results = new AccessTokenClass();
        HttpClient client = new HttpClient();

        var tokenResponse = await client.SendAsync(tokenRequest);

        json = await tokenResponse.Content.ReadAsStringAsync();
        results = JsonConvert.DeserializeObject<AccessTokenClass>(json);


        //New Block For Accessing Data from Microsoft Graph Rest API
        HttpClient _client = new HttpClient();

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.windows.net/YourTenant.onmicrosoft.com/users?api-version=1.6"));

        //Passing Token For this Request
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);

        //Check The Response and extract response data
        HttpResponseMessage response = await _client.SendAsync(request);
        dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

        return objGpraphUserList

使用的类:

 public class AccessTokenClass
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
    }

我得到了预期的用户列表。查看屏幕截图。

enter image description here

验证令牌:

https://jwt.io/上检查您的令牌,令牌应该具有User.ReadWrite.AllUser.Read.All 应用程序权限

enter image description here

注意: 您应该对Azure Active Directory Graph

具有以下权限

enter image description here
有关更多信息,请参阅this official document

希望这会有所帮助。