使用 UserCredentials 的访问令牌验证错误 MS Graph

Access token validation error MS Graph using UserCredentials

我正在尝试使用 AAD 帐户访问 MS Graph,此帐户是全局管理员并已授予所有权利。我想在没有交互式登录的情况下进行,即使用 UserPasswordCredential。尝试访问 MS Graph 时出现错误:

我的流量:

获取令牌:

public async Task<string> GetUserAccessTokenAsync()
        {
            UserPasswordCredential userPasswordCredential = new UserPasswordCredential("user@tenant.onmicrosoft.com", "password");
            AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/tenant.onmicrosoft.com");
            AuthenticationResult token = await authContext.AcquireTokenAsync("https://graph.windows.net", appId, userPasswordCredential);

            return token.AccessToken;
        }

使用令牌:

public static GraphServiceClient GetAuthenticatedClient()
        {
            GraphServiceClient graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async (requestMessage) =>
                    {
                        Adal adal = new Adal();
                        string accessToken = await adal.GetUserAccessTokenAsync();

                        // Append the access token to the request.
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                    }));
            return graphClient;
        }

正在尝试调用 MS Graph 来读取事件:

 try
        {
            // Get events.
            items = await eventsService.GetMyEvents(graphClient);
        }
        catch (ServiceException se)
        {
            //this is where I get the error
        }

委派权限:

我哪里出错了?

好吧,至少你的资源 URI 是错误的。应该是:

public async Task<string> GetUserAccessTokenAsync()
{
   UserPasswordCredential userPasswordCredential = new UserPasswordCredential("user@tenant.onmicrosoft.com", "password");
   AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/tenant.onmicrosoft.com");
   AuthenticationResult token = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", appId, userPasswordCredential);

   return token.AccessToken;
}

https://graph.windows.net/ 适用于 Azure AD Graph,而非 MS Graph。

对于 MS Graph API,您必须使用 https://graph.microsoft.com/

经过更多研究,我了解到我们需要获得管理员权限。在文档中找到:"App-only scopes (also known as app roles) grant the app the full set of privileges offered by the scope. App-only scopes are typically used by apps that run as a service without a signed-in user being present" https://graph.microsoft.io/en-us/docs/authorization/permission_scopes 我使用用户令牌获得了成功的结果,因为它处于委派权限之下。 希望这对以后的人有帮助。

经过进一步研究,我们似乎确实需要管理员权限,因为我们使用的是 App-only 范围而不是委托范围 权限。仅限应用程序范围内的基本读取操作被指定为仅限管理员。希望这可以帮助遇到同样问题的人。 https://graph.microsoft.io/en-us/docs/authorization/permission_scopes