【问题标题】:403 error received when trying to OAUTH authenticate WebClient against Microsoft Azure Graph尝试针对 Microsoft Azure Graph 对 WebClient 进行 OAUTH 身份验证时收到 403 错误
【发布时间】:2018-05-05 05:46:47
【问题描述】:

我正在尝试编写一个简单的控制台应用程序,该应用程序将使用 OAUTH 针对 Azure Graph 进行身份验证,而无需用户名/密码,但在执行 WebClient.DownloadString 方法时收到 403 错误。任何帮助将不胜感激。

 static void Main(string[] args)
 {
  //  Constants
  var tenant = "mytenant.onmicrosoft.com";
  var resource = "https://graph.microsoft.com/";
  var clientID = "blah-blah-blah-blah-blah";
  var secret = "blahblahblahblahblahblah";

  //  Ceremony
  var authority = $"https://login.microsoftonline.com/{tenant}";
  var authContext = new AuthenticationContext(authority);
  var credentials = new ClientCredential(clientID, secret);


  // Obtain Token
  var authResult = authContext.AcquireToken(resource, credentials);

  WebClient webClient1 = new WebClient();
  webClient1.Headers[HttpRequestHeader.Authorization] = "Bearer " + authResult.AccessToken;

 webClient1.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
 webClient1.Headers[HttpRequestHeader.Accept] = "application/json";

 string payload = webClient1.DownloadString("https://graph.microsoft.com/v1.0/users?$Select=givenName,surname");

  }
 }

【问题讨论】:

    标签: c# rest azure oauth-2.0 microsoft-graph-api


    【解决方案1】:

    此问题现已解决。上面的代码是正确的,但是我缺少一个步骤,就是在 Azure 中配置 ServicePrincipal:-

    1. 使用命令 Connect-Msolservice 以全局管理员身份登录
    2. 检索服务主体的 ObjectID > Get-MsolServicePrincipal –AppPrincipalId YOUR_APP_CLIENT_ID
    3. 使用 > Add-MsolRoleMember -RoleMemberType ServicePrincipal -RoleName ‘Company Administrator’ -RoleMemberObjectId YOUR_OBJECT_ID 分配角色

    以下链接也非常有用:-

    https://developer.microsoft.com/en-us/graph/docs/concepts/overview(单击左上角的箭头显示完整列表,然后向下滚动到相应的操作)

    https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-error-codes-and-error-handling

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2017-03-28
      • 2021-03-31
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      相关资源
      最近更新 更多