调用 Microsoft Graph API 获取令牌会出现错误“AADSTS900144:请求正文必须包含以下参数:‘grant_type’

Wal*_*ikk 4 c# azure-active-directory

我正在调用 Graph API URL

https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token
Run Code Online (Sandbox Code Playgroud)

获取访问令牌,但我收到以下响应。

{
    "error": "invalid_request",
    "error_description": "AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: 5ff6b053-9011-4397-89ff-fdb6f31e4600\r\nCorrelation ID: 22509847-199d-4bd8-a083-b29d8bbf3139\r\nTimestamp: 2020-04-01 11:14:00Z",
    "error_codes": [
        900144
    ],
    "timestamp": "2020-04-01 11:14:00Z",
    "trace_id": "5ff6b053-9011-4397-89ff-fdb6f31e4600",
    "correlation_id": "22509847-199d-4bd8-a083-b29d8bbf3139",
    "error_uri": "https://login.microsoftonline.com/error?code=900144"
}
Run Code Online (Sandbox Code Playgroud)

我有一个活跃的租户ID,我注册了一个应用程序,并且我有一个上述应用程序的活跃用户user@tenant.onmicrosoft.com;该用户拥有所有角色(全局管理员)。

请在下面找到邮递员的请求和响应。 邮递员快照

另外,我已按照https://learn.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=http中的建议授予 API 权限

Md *_*ron 6

问题:我已成功重现您的错误。正如您在下面看到的:

在此输入图像描述

解决方案:

你正在以错误的方式尝试。您必须form-data通过邮递员发送所需的参数,key-value pairs格式如下:

grant_type:client_credentials
client_id:b6695c7be_YourClient_Id_e6921e61f659
client_secret:Vxf1SluKbgu4PF0Nf_Your_Secret_Yp8ns4sc=
scope:https://graph.microsoft.com/.default
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

代码片段:

grant_type:client_credentials
client_id:b6695c7be_YourClient_Id_e6921e61f659
client_secret:Vxf1SluKbgu4PF0Nf_Your_Secret_Yp8ns4sc=
scope:https://graph.microsoft.com/.default
Run Code Online (Sandbox Code Playgroud)

使用的类别:

  //Token Request End Point
    string tokenUrl = $"https://login.microsoftonline.com/YourTenant.onmicrosoft.com/oauth2/v2.0/token";
    var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

    //I am Using client_credentials as It is mostly recommended
    tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        ["grant_type"] = "client_credentials",
        ["client_id"] = "b6695c7be_YourClient_Id_e6921e61f659",
        ["client_secret"] = "Vxf1SluKbgu4PF0Nf_Your_Secret_Yp8ns4sc=",
        ["scope"] = "https://graph.microsoft.com/.default" 
    });

    dynamic json;
    AccessTokenClass results = new AccessTokenClass();
    HttpClient client = new HttpClient();

    var tokenResponse = await client.SendAsync(tokenRequest);

    json = await tokenResponse.Content.ReadAsStringAsync();
    results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
Run Code Online (Sandbox Code Playgroud)

你可以参考官方文档

希望这会有所帮助。如果您仍有任何疑虑,请随时分享。