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

问题描述 投票:0回答:2

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

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

enter image description here

然后,我使用此端点/ 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中有效。为现有组创建Team实例效果很好。

谢谢!

c# microsoft-graph azure-ad-graph-api
2个回答
0
投票

似乎您在代码中使用了客户端凭据授予流,但是graph api仅支持委托权限。因此,我们需要使用授权码授予流程或用户名/密码授予流程。 (顺便说一句,我们建议使用授权码流而不是用户名/密码流)

有关授权代码流程,请参阅此tutorial及其代码示例。

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

AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);

对于用户名/密码流,您可以在其中带有代码示例的情况下引用此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();

希望有帮助〜


0
投票

我已尝试使用证书创建身份验证。首先,在“应用程序注册”中应用该配置(仅具有应用程序权限)并从您之前共享的链接中阅读了一些指南之后,我从/ Groups获得了成功。之后,向/ Groups / {XXX-XX} / Planner / Plans创建一个新请求,并获得权限错误。

这是获取所有组的代码。

var url = "https://graph.microsoft.com";
var auth = new Authorization(ConfigurationParameters.TenantID, 
                            ConfigurationParameters.ClientID,
                            "‎34 64 03 a4 9c ad xx xx xx xx xx xx xx xx xx xx xx xx xx xx", 
                            @"C:\temp\Certificate.pfx", 
                            "Come up with something secure!");
var accessToken =  auth.GetAccessTokenAsync(url).Result;
using (var httpClient = new HttpClient())
{

    httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    string urlReq = "https://graph.microsoft.com/v1.0/groups/" + createPlannerForGroupRequest.GroupId.ToString() + "";
    var response = httpClient.GetAsync(urlReq);
    Stream receiveStream = response.Result.Content.ReadAsStreamAsync().Result;
    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
    var r = readStream.ReadToEnd();
    return r;
 }

这很有效,我可以阅读要求的小组,但是当我应用此端点时:

string urlReq = "https://graph.microsoft.com/v1.0/groups/" + createPlannerForGroupRequest.GroupId.ToString() + "/planner/plans";

我收到此错误消息:

{
  "error": {
    "code": "UnknownError",
    "message": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"/>\r\n<title>403 - Forbidden: Access is denied.</title>\r\n<style type=\"text/css\">\r\n<!--\r\nbody{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}\r\nfieldset{padding:0 15px 10px 15px;} \r\nh1{font-size:2.4em;margin:0;color:#FFF;}\r\nh2{font-size:1.7em;margin:0;color:#CC0000;} \r\nh3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} \r\n#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:\"trebuchet MS\", Verdana, sans-serif;color:#FFF;\r\nbackground-color:#555555;}\r\n#content{margin:0 0 0 2%;position:relative;}\r\n.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}\r\n-->\r\n</style>\r\n</head>\r\n<body>\r\n<div id=\"header\"><h1>Server Error</h1></div>\r\n<div id=\"content\">\r\n <div class=\"content-container\"><fieldset>\r\n  <h2>403 - Forbidden: Access is denied.</h2>\r\n  <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>\r\n </fieldset></div>\r\n</div>\r\n</body>\r\n</html>\r\n",
    "innerError": {
      "request-id": "3ddaf510-6c16-403e-a365-4f2c6f27032c",
      "date": "2020-06-05T06:08:24"
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.