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

时间:2020-04-01 11:39:23

标签: c# azure-active-directory

我正在调用Graph API URL

https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token

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

{
    "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"
}

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

请在下面找到邮递员的要求和回复。 PostmanSnap

我也按照https://docs.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=http

中的建议授予了API权限

1 个答案:

答案 0 :(得分:0)

问题: :我已成功复制了您的错误。如下所示:

enter image description here

解决方案:

您尝试的方式有误。您必须在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

enter image description here

代码段:

  //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);

使用的类:

public class AccessTokenClass
   {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
   }

您可以参考Official document

希望有帮助。如果您还有任何顾虑,请随时分享。