Azure active directory 无法基于访问令牌对用户进行身份验证-MS Graph API C

Azure active directory 无法基于访问令牌对用户进行身份验证-MS Graph API C,azure-active-directory,access-token,microsoft-graph-api,azure-ad-graph-api,Azure Active Directory,Access Token,Microsoft Graph Api,Azure Ad Graph Api,我正在尝试使用Graph API获取当前用户的数据。我想获取访问令牌并将其附加到请求消息中。所以我想跳过登录界面。由于某种原因,我得到了401未经授权的错误,无效的用户。。。我在那里注册了我的appmvc AAD,以及密码、客户id和租户id 这是获取令牌的方法: public static string GetToken() { string authority = "https://graph.microsoft.com/{tenantID}/oauth2/t

我正在尝试使用Graph API获取当前用户的数据。我想获取访问令牌并将其附加到请求消息中。所以我想跳过登录界面。由于某种原因,我得到了401未经授权的错误,无效的用户。。。我在那里注册了我的appmvc AAD,以及密码、客户id和租户id

这是获取令牌的方法:

    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;
    }

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

Azure AD发布了两种访问令牌

第一种是委托令牌,用于委托用户操作用户的资源

另一个是应用令牌,通常用于对所有组织的资源执行操作,该令牌中没有用户contextcurrent user。因此,我们不应该使用这个令牌来执行需要用户上下文的资源as me

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

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

这个问题解决了吗?如果不是,我认为你使用的权限不对。如果您的资源是,则您的权限应该是或相同的权限,但将公用替换为您的azure AD租户ID。来自的信息我有类似的方法。var user=graphClient.Users[uid].Request.SelectdisplayName.GetAsync;在调用GetAuthenticatedClient方法之后,我这样调用它:GraphServiceClient graphClient=SDKHelper.GetAuthenticatedClient;ViewBag.Name=graphService.GetMyNamegraphClient;要从Azure active directory读取用户资源,我们需要授予User.read.All;Directory.Read.All;应用程序的权限。请检查Azure门户上的权限,以确保您已授予足够的权限。修改权限后,您可以通过解码令牌来检查这些权限。请确保令牌中存在相对作用域?如果问题仍然存在,您是否介意共享详细的错误消息?相对范围?是的,您可以通过从中解码令牌来检查角色声明。