C# 的图表 API:401 - 未经授权:由于凭据无效,访问被拒绝。在 /planner/plans

Graph API for C#: 401 - Unauthorized: Access is denied due to invalid credentials. on /planner/plans

我正在使用 Graph API。我对此没有太多经验。我正在创建一个应用程序以将计划添加到现有组中。

所以,我已经注册了一个具有此权限的应用程序(您可以看到这些是委托权限):

然后,我编写了这段代码以使用此端点 /planner/plans 添加一个新的 Planner(您会看到我正在使用令牌)。

var configAuthority = "https://login.microsoftonline.com/8318d89e-e4db-471e-85da-b34ae833813f";
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                  .Create(ConfigurationParameters.ClientID)
                                  .WithTenantId(ConfigurationParameters.TenantID)
                                  .WithClientSecret(ConfigurationParameters.ClientSecret)
                                  .WithAuthority(new Uri(configAuthority))
                                  .Build();
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            AuthenticationResult accessToken = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().Result;
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);
            List<HeaderOption> requestHeaders = new List<HeaderOption>() {
                            new HeaderOption("Authorization", "Bearer " + accessToken.AccessToken)
                };
            var existingsplanners = graphClient
                                        .Groups[createPlannerForGroupRequest.GroupId.ToString()]
                                        .Planner
                                        .Plans.
                                        Request(requestHeaders)
                                        .GetAsync()
                                        .Result;
            var planner = graphClient
                        .Groups[createPlannerForGroupRequest.GroupId.ToString()]
                        .Planner
                        .Plans
                        .Request(requestHeaders)
                        .AddAsync(new PlannerPlan { 
                            Title = createPlannerForGroupRequest.Name,
                            Owner = createPlannerForGroupRequest.GroupId.ToString(),
                            ODataType = null,
                        }).Result;

两个请求的结果相同。

Code: UnknownError
Message: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>401 - Unauthorized: Access is denied due to invalid credentials.</h2>
  <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
 </fieldset></div>
</div>
</body>
</html>

Inner error:
    AdditionalData:
    request-id: 19c09b10-1694-4201-85a9-ba3639e1dba5
    date: 2020-06-03T07:29:59
ClientRequestId: 19c09b10-1694-4201-85a9-ba3639e1dba5

如您所见,即使是 Azure AD 上的委派权限,也存在权限问题。我应该等24小时吗?我应该更改令牌请求方方法而不是使用 AcquireTokenForClient 吗?

同样的方法适用于 Graph Explorer。为现有组创建团队实例工作正常。

谢谢!

您似乎在代码中使用了客户端凭据授予流程,但图表 api 仅支持委派权限。所以我们需要使用授权码授权流程或username/password授权流程。 (顺便说一句,我们推荐授权码流而不是username/password流)

授权代码流程,请参考这个tutorial,里面有代码示例。

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithRedirectUri(redirectUri)
    .WithClientSecret(clientSecret) // or .WithCertificate(certificate)
    .Build();

AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);

对于username/password流程,你可以参考这个tutorial里面的代码示例

IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantID)
            .Build();

UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

GraphServiceClient graphClient = new GraphServiceClient(authProvider);

User me = await graphClient.Me.Request()
                .WithUsernamePassword(email, password)
                .GetAsync();

更新:

您可以按照以下步骤进行一些更改,这样您就不需要在代码中提供client_secret,它也不会显示错误消息The request body must contain the following parameter: 'client_assertion' or 'client_secret'

  1. 转到您在 azure ad 中注册的应用,然后单击 "Authentication" --> "Add a platform" --> "Mobile and desktop applications"。

  2. 选择第一个作为"Redirect URIs"。

  3. 向下滚动查看此配置是否为"yes"(如果"no",请将其更改为"yes"),然后单击"Save"。