您无权查看此目录或页面未授权 401

You do not have permission to view this directory or page unauthorized 401

我在 Azure 中有一个 Web 应用程序 运行,它启用了 Azure Active Directory 身份验证。下面给出(我已经正确配置了这个没有问题):-

现在我想调用此网络应用程序的 API 之一。根据客户端凭据获取访问令牌的代码:-

public static string GetAccessToken()
        {
            string authContextURL = "https://login.microsoftonline.com/" + "TENANT_ID";
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential("CLIENT_ID", "CLIENT_SECRET");
            var result = authenticationContext.AcquireTokenAsync("URL_FOR_MY_WEBAPP", credential).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the token");
            }

            string token = result.AccessToken;
            return token;
        }

调用所需 API 的代码:-

private static string GET(string URI, string token)
        {
            Uri uri = new Uri(string.Format(URI));

            // Create the request
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";

            // Get the response
            HttpWebResponse httpResponse;
            try
            {
                httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            string result = null;
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }

            return result;
        }

我在获取响应时遇到未经授权的错误。谁能告诉我这里出了什么问题?相同的服务主体正在使用图形客户端。任何帮助或建议将不胜感激。

获取访问令牌的资源不正确。您应该使用与您的 AD 应用程序相同的客户端 ID。

var result = authenticationContext.AcquireTokenAsync("{CLIENT_ID}", credential).Result;