错误消息:“ Authorization_RequestDenied”,“权限不足,无法完成操作

时间:2019-06-16 10:07:25

标签: microsoft-graph azure-ad-graph-api microsoft-graph-mail

我正在创建一个控制台c#应用程序,并使用以下代码访问我的电子邮件对象。这是我的第一个应用程序。我能够生成令牌,但是之后我得到的权限错误不足。

  

{“ odata.error”:{“ code”:“ Authorization_RequestDenied”,“ message”:{“ lang”:“ en”,“ value”:“权限不足,无法完成操作。”},“ requestId” :“ aa24be4b-9d63-4460-83ef-9095d21fb483”,“日期”:“ 2019-06-16T10:07:06”}}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Net.Http;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;

namespace ConsoleTestApp
{
    class Program
    {
        private const string _clientId = "hiddenforprivacy";
        public const string _aadInstance = "https://login.microsoftonline.com/{0}";        
        public const string _tenantId = "hiddenforprivacy";
        public const string _resource = "https://graph.windows.net";
        public const string _appKey = "hiddenforprivacy";
        static string authority = string.Format(CultureInfo.InvariantCulture, _aadInstance, _tenantId);

        private static HttpClient _httpClient = new HttpClient();
        private static AuthenticationContext _context = null;
        private static ClientCredential _credential = null;


        static void Main(string[] args)
        {
            _context = new AuthenticationContext(authority);
            _credential = new ClientCredential(_clientId, _appKey);
            Task<string> _token = GetToken();
            _token.Wait();
            Console.WriteLine(_token.Result);

            Task<string> _users = GetUsers(_token.Result);
            _users.Wait();
            Console.WriteLine(_users.Result);
            Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result)
        {
            string _users1 = null;
            string _queryString = "api-version=1.6";
            var _uri = "https://graph.windows.net/TENANT-ID/users?" + _queryString;

            _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result);
            var _getResult = await _httpClient.GetAsync(_uri);
            if (_getResult != null)
            {
                _users1 = await _getResult.Content.ReadAsStringAsync();
            }
            return _users1;
        }

        private static async Task<string> GetToken()
        {
            AuthenticationResult _result = null;
            string _token2 = null;
            _result = await _context.AcquireTokenAsync(_resource, _credential);
            _token2 = _result.AccessToken;
            return _token2;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您正在使用客户端凭据流,因此您需要授予应用程序类型权限。看来您已授予委派权限,但您需要授予应用程序权限。

enter image description here

顺便说一句,我们强烈建议您使用Microsoft Graph而非Azure AD Graph API来访问Azure Active Directory资源。