我正在尝试获取天蓝色的用户,并且遇到权限错误,即使不是我放置我的用户,为什么?不应该是我不需要管理员同意的东西吗?任何帮助表示赞赏!
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create("****")
.WithTenantId("****")
.WithClientSecret("***")
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
// Create a new instance of GraphServiceClient with the authentication provider.
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var user = await graphClient.Users
.Request()
.WithScopes(graphScopes)
.Select(u => new {
u.DisplayName
})
.GetAsync();
```
对于此问题,您似乎无权获取用户。您可以参考图api的文档,需要如下所示的权限:
因此,请转到在您的天蓝色广告中注册的应用程序,然后单击“ API权限”,然后在其中添加权限。
After add the permissions, please do not forget click "Grand admin consent for xxx".
For the question why it still failed when you change the Users
to me
. You use client credential flow to do authentication to request the graph api, you just provide the information of clientId
, tenantId
and clientSecret
. So it doesn't contain a user(or yourself) information. So you can't use .Me
. If you want to use .Me
, you can use password grant flow. It contains the user information, so system know who is .Me
.
================================Update==============================
如果您要使用委托权限(例如User.ReadBasic.All
),则不能使用client_credential。现在您的代码使用client_credential流,访问令牌不包含用户身份。我在下面提供了一个用户名/密码流示例(并使用委托权限User.ReadBasic.All
)供您参考f:
在已注册应用的“ API权限”标签中,我只添加一个权限User.ReadBasic.All
。
代码如下图所示:
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Security;
namespace ConsoleApp3
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create("<clientId>")
.WithTenantId("<tenantId>")
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var str = "<your password>";
var password = new SecureString();
foreach (char c in str) password.AppendChar(c);
var users = await graphClient.Users.Request().WithUsernamePassword("<your account/email>", password).GetAsync();
Console.WriteLine(users.Count);
}
}
}
并且在运行代码之前,您需要做一次“同意使用该应用程序”。您需要按以下方式浏览网址:https://login.microsoftonline.com/<tenantId>/oauth2/v2.0/authorize?client_id=<clientId>&response_type=code&redirect_uri=<redirectUri>&response_mode=query&scope=openid https://graph.microsoft.com/.default&state=12345
在浏览器中,页面将显示为:
单击“接受”,然后可以运行代码以获取成功的用户列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句