Microsoft Graph Api-询问我时没有权限访问令牌

时间:2019-08-07 13:18:40

标签: c# azure model-view-controller azure-active-directory microsoft-graph

使用Microsoft graph api时,我确保我拥有获取用户个人资料照片的所有权限,但是每次都会收到“没有权限令牌”错误。它没有意义,因为我可以使用相同的令牌检索所有其他信息,例如DirectReports a Manager。

我尝试了不同的端点和不同的呼叫,例如Me.Photo.Content和Users [id] .Photo-但还是没有运气

ProfilePhoto GetAvatarForCurrentUser(GraphServiceClient  _graphServiceClient)
    {

        using (var task = Task.Run(async () => await _graphServiceClient.Me.Photo.Request().GetAsync()))
        {
            while (!task.IsCompleted)
                Thread.Sleep(1000);

            var avatar = task.Result;
            return avatar;
        }     
    }



public ProfilePhoto GetAvatar()
    {
        var accessToken = GetAppTokenForAvatar();
        var graphserviceClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(
        (requestMessage) =>
     {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            return Task.FromResult(0);
        }));

        var userAvatar = GetAvatarForCurrentUser(graphserviceClient);

        return userAvatar as Microsoft.Graph.ProfilePhoto;
     }



public string GetAppTokenForAvatar()
     {
        AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/[app-id]/");

        ClientCredential clientCred = new ClientCredential(Config.AdClientID, Config.AdClientKey);
        AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCred).Result;
        return authenticationResult.AccessToken;
     }

我希望重新获得自己的个人资料头像,就像我说的那样,获取Menager或其他相关数据没有问题。

1 个答案:

答案 0 :(得分:1)

AuthenticationContext不正确。当您使用错误的AuthenticationContext时,您将遇到此类错误。

enter image description here

替换

AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/[app-id]/");

使用

AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/[tenant-id]/");

根据您的代码,您正在使用客户端凭据,应使用Users[id].Photo。并确保您授予管理员同意的应用程序许可权。

enter image description here