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



我正在尝试编写一个简单的控制台应用程序,该应用程序将在不需要用户名/密码的情况下使用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");
}
}

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

  1. 使用命令Connect Msolservice与全局管理员登录
  2. 检索服务主体的ObjectID>获取MsolServicePrincipal–AppPrincipalId YOUR_APP_CLIENT_ID
  3. 使用>添加MsolRoleMember-RoleMemberType ServicePrincipal-RoleName"公司管理员"-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

最新更新