无法根据访问令牌对用户进行身份验证 - MS Graph API C#

Fail to authenticate user based on access token - MS Graph API C#

我正在尝试使用 Graph API 获取当前用户的数据。我想获取访问令牌并将其附加到请求消息中。所以我想跳过登录 UI。出于某种原因,我收到 (401) 未经授权的错误,无效用户...我注册了我的应用程序 (mvc) AAD,并从那里注册了密码、客户端 ID、租户 ID。

这是获取token的方法:

    public static string GetToken()
    {
        string authority = "https://graph.microsoft.com/{tenantID}/oauth2/token";
        string clientId = "client id";
        string secret = "client secret";
        string resource = "https://graph.microsoft.com";

        AuthenticationContext authContext = new AuthenticationContext(authority);

        ClientCredential clientCredential = new ClientCredential(clientId, secret);
        AuthenticationResult authResult = authContext.AcquireToken(resource, clientCredential);
        return authResult.AccessToken;
    }

这是代码,我在其中附加了访问令牌:

    public static GraphServiceClient GetAuthenticatedClient()
    {
        GraphServiceClient graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    string accessToken = GetToken();
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                }));
        return graphClient;
    }

任何建议都会有所帮助,因为我不知道。

A​​zure AD 颁发了两种访问令牌。

第一个是delegate-token,用来委托用户操作用户的资源

还有一个是application token,通常用于对所有组织的资源执行操作,这个token中没有用户上下文(当前用户)。所以我们不应该使用这个令牌来执行资源,因为 me 需要用户上下文。

要使用应用程序令牌操作资源,我们需要使用用户集合指定用户,如下代码:

string userId = "";
var user = graphserviceClient.Users[userId].Request().GetAsync().Result;

这个问题解决了吗?如果没有,我认为您没有使用正确的权限。如果您的资源是“https://graph.microsoft.com/" then your authority should be "https://login.windows.net/common/oauth2/v2.0/token" or the same authority but swap "common" for your azure AD tenant ID. Info from here