【问题标题】:Fail to authenticate user based on access token - MS Graph API C#无法根据访问令牌对用户进行身份验证 - MS Graph API C#
【发布时间】:2023-03-21 08:55:01
【问题描述】:

我正在尝试使用 Graph API 获取当前用户的数据。我想获取访问令牌并将其附加到请求消息中。所以我想跳过登录用户界面。某些原因我收到 (401) Unauthorized 错误,无效用户...我从那里注册了我的 app(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;
    }

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

【问题讨论】:

    标签: azure-active-directory access-token microsoft-graph-api azure-ad-graph-api


    【解决方案1】:

    Azure AD 颁发的访问令牌有两种。

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

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

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

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

    【讨论】:

    • 我有这样的方法。 var user = graphClient.Users[uid].Request().Select("displayName").GetAsync();我在调用 GetAuthenticatedClient 方法之后调用它: GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient(); ViewBag.Name = graphService.GetMyName(graphClient);
    • 要从 Azure Active Directory 中读取来自用户的资源,我们需要为应用授予 User.Read.All; Directory.Read.All; 权限。请检查 Azure 门户上的权限,以确保您已授予足够的权限。修改权限后,您可以通过从this site 解码令牌来检查这些权限。
    • 请确保令牌中存在相对范围?如果问题仍然存在,您介意分享详细的错误消息吗?
    • 相对范围?
    • 是的,您可以通过解码来自this site 的令牌来检查roles 声明。
    【解决方案2】:

    解决了吗?如果没有,我认为您使用的权限不正确。如果您的资源是“https://graph.microsoft.com/”,那么您的权限应该是“https://login.windows.net/common/oauth2/v2.0/token”或相同的权限,但将“common”交换为您的 azure AD 租户 ID。来自here的信息

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 2018-04-18
      • 2014-02-11
      相关资源
      最近更新 更多