1

我正在创建一个控制台 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;
        }
    }
}
4

1 回答 1

1

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

在此处输入图像描述

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

于 2019-06-17T01:27:26.393 回答