尽管查询字符串中为grant_type,Microsoft Graph API返回404错误缺少参数

时间:2019-01-21 22:58:38

标签: javascript microsoft-graph

通过本教程的第4部分调用Microsoft Graph API来获取访问令牌:https://docs.microsoft.com/en-us/graph/auth-v2-service?view=graph-rest-1.0

我正在执行以下提取请求:

  var options = {
    "method": "POST",
    "contentType": "application/x-www-form-urlencoded",
    "accept": 'application/json',
    "headers": {
      'Content-Type': "application/x-www-form-urlencoded",
    },
  }
  var authorization_url = "https://login.microsoftonline.com/" + tenant + 
    "/oauth2/v2.0/token/" + 
      "client_id=" + client_id + 
        "&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default" +
          "&client_secret=" + client_secret + 
              "&grant_type=client_credentials";

完全有信心我的所有参数都是正确的,但是它返回无效的请求错误:“请求正文必须包含以下参数:'grant_type'”。知道有什么问题吗?

2 个答案:

答案 0 :(得分:2)

您的authorization_url仅应包含端点(即无查询字符串):

var authorization_url = "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/token/"

参数属于POST的主体:

var payload = 
    "client_id=" + client_id + 
    "&client_secret=" + client_secret + 
    "&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default" +
    "&grant_type=client_credentials";

(您的options对我来说还不错)

答案 1 :(得分:0)

我怀疑您参考了token requestthat page部分。

它显示了HTTP请求的以下表示形式:

// Line breaks are for legibility only.

POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=qWgdYAmab0YSkuL1qKv5bPX
&grant_type=client_credentials

最低部分代表HTTP请求的正文,而不是URL查询字符串中传递的参数。

我建议您更改代码以适应这些更改。