尝试OAUTH针对Microsoft Azure Graph验证WebClient时收到403错误

时间:2017-11-21 16:58:23

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

我正在尝试编写一个简单的控制台应用程序,该应用程序将使用针对Azure Graph的OAUTH进行身份验证,而无需用户名/密码,但我在执行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");

  }
 }

1 个答案:

答案 0 :(得分:0)

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

  1. 使用Connect-Msolservice命令
  2. 登录全局管理员
  3. 检索服务主体的ObjectID> Get-MsolServicePrincipal -AppPrincipalId YOUR_APP_CLIENT_ID
  4. 使用>分配角色Add-MsolRoleMember -RoleMemberType ServicePrincipal -RoleName'公司管理员'-RoleMemberObjectId YOUR_OBJECT_ID
  5. 以下链接也非常有用: -

    EntityType Symfony documentation(单击左上角的箭头显示完整列表,然后向下滚动到相应的操作)

    https://developer.microsoft.com/en-us/graph/docs/concepts/overview