【问题标题】:You do not have permission to view this directory or page unauthorized 401您无权查看此目录或页面未授权 401
【发布时间】:2020-04-07 09:07:36
【问题描述】:

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

现在我想调用这个网络应用的 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;
        }

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

【问题讨论】:

    标签: c# azure azure-active-directory adal azure-webapps


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 2021-01-29
      • 2021-01-07
      • 1970-01-01
      相关资源
      最近更新 更多